(function ($) {
    "use strict"; // Start of use strict

    //#region “结果” 标签关闭现实直到提交后
    const resultAnchor = document.getElementById("result_anchor");
    resultAnchor.setAttribute("herf", "javascript:return false;");
    resultAnchor.style.cursor = "default";
    resultAnchor.style.opacity = "0.2";

    const resultView = document.getElementById('result');
    const rawDisplayResult = resultView.style.display;
    resultView.style.display = "none";
    //#endregion

    // Smooth scrolling using jQuery easing
    $('a.js-scroll-trigger[href*="#"]:not([href="#"])').click(function () {
        if (
            location.pathname.replace(/^\//, "") ==
            this.pathname.replace(/^\//, "") &&
            location.hostname == this.hostname
        ) {
            var target = $(this.hash);
            target = target.length ?
                target :
                $("[name=" + this.hash.slice(1) + "]");
            if (target.length) {
                $("html, body").animate({
                        scrollTop: target.offset().top,
                    },
                    1000,
                    "easeInOutExpo"
                );
                return false;
            }
        }
    });

    // Closes responsive menu when a scroll trigger link is clicked
    $(".js-scroll-trigger").click(function () {
        $(".navbar-collapse").collapse("hide");
    });

    const fromElement = document.getElementById("big5personquestion")
    const QuestionNumber = fromElement.length / 5 /* 定长选项数目 */;
    const QuestionNumberSelected = []; /* placement  */

    for (let index = 0; index < QuestionNumber; index++) {
        QuestionNumberSelected.push(0);
    }

    let isFull = true;
    let fisrtFullQuestion = 0;
    let clicked = false;
    // 提交表单事件
    $('#summit').click(() => {
        for (let index = 0; index < QuestionNumber; index++) {
            for (let inputIndex = 0; inputIndex < 5; inputIndex++) {
                if (fromElement[index * 5 + inputIndex].checked) {
                    QuestionNumberSelected[index] = inputIndex + 1 /* index = value */;
                    break;
                }
                if (inputIndex == 4 && QuestionNumberSelected[index] === 0) {
                    isFull = false;
                    fisrtFullQuestion = index + 1;
                }
            }

            if (!isFull) break;
        }

        clicked = true;
        if (!isFull) {
            alert("仍有题目未答，请从第" + fisrtFullQuestion + "题开始");
            fisrtFullQuestion = 0;
            isFull = true;
            return;
        }
        console.log("开始发送请求到后端");
        // 遍历解析后的列表数组
        // for (var i = 0; i < QuestionNumberSelected.length; i++) {
        //     console.log("请求参数为：" + QuestionNumberSelected[i] + ",");
        // }
        // 发送 POST 请求给后端处理
        $.ajax({
            type: 'POST',
            url: 'http://localhost:8082/gkgk/cal',
            data: JSON.stringify(QuestionNumberSelected), // 将选中的选项转换为 JSON 字符串
            contentType: 'application/json',
            success: function (response) {
                // 处理后端返回的响应
                console.log("后端返回结果为" + response);
                var res = JSON.parse(response);
                //各种人格得分
                var score = res.scores
                console.log("总得分为:" + res.tot);
                console.log("最突出的人格为" + res.most_per);
                console.log("较适合的职业为" + res.work);

                const ctx = document.getElementById("cv").getContext("2d");
                var radarChartData = {
                    labels: ["敏感型", "外向型", "开放型", "宜人型", "尽责型"],
                    datasets: [{
                        label: "My First dataset",
                        fillColor: "rgba(151,187,205,0.2)",
                        strokeColor: "rgba(151,187,205,1)",
                        pointColor: "rgba(151,187,205,1)",
                        pointStrokeColor: "#fff",
                        pointHighlightFill: "#fff",
                        pointHighlightStroke: "rgba(220,220,220,1)",
                        data: [score.neu, score.ext, score.ope, score.agr, score.con]
                    }]
                };

                //测验结果
                const dict = [{
                    x: "敏感性",
                    y: score.neu
                },
                    {
                        x: "外向型",
                        y: score.ext
                    },
                    {
                        x: "开放型",
                        y: score.ope
                    },
                    {
                        x: "宜人型",
                        y: score.agr
                    },
                    {
                        x: "尽责型",
                        y: score.con
                    }]

                resultAnchor.setAttribute("herf", "#result");
                resultAnchor.style.cursor = "default";
                resultAnchor.style.opacity = "1";
                resultView.style.display = rawDisplayResult;
                window.location.href = "#result"
                //最突出的性格特点
                document.getElementById('personality_tex').innerText = res.most_per;
                //较适合的职业
                document.getElementById('coo_tex').innerText = res.work;
                new Chart(ctx).Radar(radarChartData, {
                    responsive: true
                });
            },
            error: function (error) {
                // 处理错误
                console.log("后端处理异常:" + error);
            }
        });
    })
    $("body").scrollspy({
        target: "#sideNav",
    });
})(jQuery);